<script setup lang="tsx">
import { ref, inject, computed } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { getList, add, edit, getInfo, fund, getIP } from '@/api/member/memberAdmin';
import { getDestList } from '@/api/member/position';
import { getDictionaries } from '@/api/member/deposit';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    title: '账号',
    colKey: 'userName',
    fixed: 'left' as const,
    width: 120,
  },
  {
    title: '备注',
    colKey: 'remark',
    width: 120,
    ellipsis: true,
    fixed: 'left' as const,
  },
  {
    title: 'UID',
    colKey: 'uid',
  },
  {
    title: '直接上级',
    colKey: 'sid',
    width: 180,
  },
  {
    title: '代理',
    colKey: 'team',
  },
  {
    title: '等级',
    colKey: 'vname',
  },
  {
    title: '是否有效',
    colKey: 'available',
  },
  {
    title: '余额',
    colKey: 'balance',
  },
  {
    title: '总充值',
    colKey: 'totalRecharge',
  },
  {
    title: '总提现',
    colKey: 'totalWithdrawals',
  },
  {
    title: '信用值',
    colKey: 'credit',
  },
  {
    title: '在离状态',
    colKey: 'isOnline',
  },
  {
    title: '账号状态',
    colKey: 'state',
    cell: (h: any, { row }: { row: any }) => {
      return (
        <Space>
          {row.state == 'Normal' && (
            <t-tag theme="primary" variant="light">
              正常
            </t-tag>
          )}
          {row.state == 'Locked' && (
            <t-tag theme="warning" variant="light">
              锁定
            </t-tag>
          )}
          {row.state == 'Frozen' && (
            <t-tag theme="danger" variant="light">
              冻结
            </t-tag>
          )}
          {row.state == 'Kicked' && <t-tag theme="danger">踢下线</t-tag>}
        </Space>
      );
    },
  },
  {
    title: '注册时间',
    colKey: 'regTime',
    width: 180,
  },
  {
    title: '最后登录时间',
    colKey: 'lastLogin',
    width: 180,
  },
  {
    title: '注册IP',
    colKey: 'zcIp',
    width: 180,
  },
  {
    title: '最后登录IP',
    colKey: 'lastIp',
    width: 180,
  },
  {
    title: '账号锁定',
    colKey: 'state',
    width: 100,
  },
  {
    title: '风险账户',
    colKey: 'danger',
    width: 100,
  },
  {
    title: '操作',
    colKey: 'op',
    width: 250,
    fixed: 'right' as const,
  },
];

const footData = computed(() => {
  const totalMoney = data.value.reduce((sum, item) => sum + (item.balance || 0), 0);
  const totalMoney2 = data.value.reduce((sum, item) => sum + (item.totalRecharge || 0), 0);
  const totalMoney3 = data.value.reduce((sum, item) => sum + (item.totalWithdrawals || 0), 0);

  return [
    {
      userName: '合计',
      // 格式化显示
      balance: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalMoney),
      totalRecharge: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalMoney2),
      totalWithdrawals: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalMoney3),
    },
  ];
});

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  userType: string | null;
  vipLevel: string | null;
  userName: string | null;
  realName: string | null;
  zcIp: string | number | null;
  lastIp: string | number | null;
  uid: string | number | null;
  sid: string | number | null;
  danger: string | number | null;
  balance1: string | number | null;
  balance2: string | number | null;
  state: string | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  userType: undefined,
  vipLevel: undefined,
  userName: undefined,
  realName: undefined,
  zcIp: undefined,
  lastIp: undefined,
  uid: undefined,
  sid: undefined,
  danger: undefined,
  balance1: undefined,
  balance2: undefined,
  state: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-select v-model={queryForm.value.userType} placeholder="账户类型">
        <t-option key="Agency" label="代理" value="Agency" />
        <t-option key="Member" label="会员" value="Member" />
        <t-option key="Test" label="测试" value="Test" />
      </t-select>
      <t-select v-model={queryForm.value.vipLevel} placeholder="会员等级">
        {gradeList.value?.map((item) => (
          <t-option key={item.grade.toString()} label={item.name} value={item.grade.toString()} />
        ))}
      </t-select>
      <t-input v-model={queryForm.value.userName} placeholder="账号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.uid} placeholder="UID" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.sid} placeholder="推荐人UID" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.state} placeholder="账户状态">
        <t-option key="Normal" label="正常" value="Normal" />
        <t-option key="Locked" label="锁定" value="Locked" />
        <t-option key="Frozen" label="冻结" value="Frozen" />
        <t-option key="Kicked" label="踢下线" value="Kicked" />
      </t-select>
      <t-select v-model={queryForm.value.danger} placeholder="风险账户">
        <t-option key={1} label="是" value={1} />
        <t-option key={0} label="否" value={0} />
      </t-select>
      <t-date-range-picker v-model={dateRange.value} placeholder="注册时间" />
      <t-input v-model={queryForm.value.realName} placeholder="真实姓名" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.zcIp} placeholder="注册IP" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.lastIp} placeholder="登录IP" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-range-input
        style="width: 240px;"
        onChange={(newVal: any) => {
          queryForm.value.balance1 = newVal[0];
          queryForm.value.balance2 = newVal[1];
        }}
        v-model={balanceRange.value}
        placeholder="余额"
      />
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="id"
      onUnGetList={unGetList}
      footData={footData.value}
    >
      {{
        available: (slotProps: any) => <div>{slotProps.row.available == 0 ? '否' : '是'}</div>,
        balance: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.balance,
            )}
          </div>
        ),
        totalRecharge: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.totalRecharge,
            )}
          </div>
        ),
        totalWithdrawals: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.totalWithdrawals,
            )}
          </div>
        ),
        isOnline: (slotProps: any) => <div>{slotProps.row.isOnline == 0 ? '离线' : '在线'}</div>,
        state: (slotProps: any) => (
          <t-switch
            key={slotProps.row.id}
            value={slotProps.row.state}
            onChange={() => unEditChange(slotProps, 'state')}
            disabled={slotProps.row.state == 'Frozen' || slotProps.row.state == 'Kicked'}
            size="large"
            customValue={['Locked', 'Normal', 'Frozen', 'Kicked', null]}
            label={['是', '否']}
          ></t-switch>
        ),
        danger: (slotProps: any) => (
          <t-switch
            key={slotProps.row.id}
            value={slotProps.row.danger}
            onChange={() => unEditChange(slotProps, 'danger')}
            size="large"
            customValue={[1, 0]}
            label={['是', '否']}
          ></t-switch>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="success" onClick={() => unCapital(slotProps)}>
              资金
            </Link>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => unIpCheck(slotProps)}>
              IP检测
            </Link>
            <Link theme="warning" onClick={() => unTeamTask(slotProps)}>
              团队任务
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

// 切换状态
const unEditChange = async (slotProps: any, key: string) => {
  if (key == 'state') {
    slotProps.row.state = slotProps.row.state == 'Normal' ? 'Locked' : 'Normal';
  } else if (key == 'danger') {
    slotProps.row.danger = slotProps.row.danger == 0 ? 1 : 0;
  }
  edit(slotProps.row).then(() => {
    MessagePlugin.success('操作成功');
    unGetList();
  });
};

// 等级列表
import { useGradeStore } from '@/store/modules/member';
const gradeStore = useGradeStore();
const gradeList = ref<any[]>([]);
gradeList.value = gradeStore.gradeList;

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetList();

const typeList = ref([]);
// 获取类型
const unGetDictionaries = () => {
  getDictionaries({}).then((res) => {
    typeList.value = res.data;
  });
};
unGetDictionaries();

// 获取职位
const destList = ref([]);
const unGetDestList = async () => {
  try {
    const res = await getDestList({
      pageNum: 1,
      pageSize: 999,
    });
    destList.value = res.rows;
  } catch (e) {
    console.log(e);
  }
};
unGetDestList();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  balanceRange.value = [null, null];
  dateRange.value = [];
  unGetList();
};
/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加账户', {}, '添加账户');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加账户',
  '添加账户',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    userType: [{ required: true, message: '账户类型不能为空', trigger: 'change' }],
    userName: [{ required: true, message: '账户名称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        validator: (val: string) => val.length >= 6 && val.length <= 18,
        message: '密码长度应介于6至18位之间',
        trigger: 'blur',
      },
    ],
    confirmPassword: [{ required: true, message: '确认密码不能为空', trigger: 'blur' }],
  },
);

// 账户详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.id);
    res.data.password = undefined;
    res.data.fundPassword = undefined;
    formObj.show(
      '编辑账户',
      {
        ...res.data,
      },
      `编辑账户 - ID：${slotProps.row.id}\u00A0\u00A0\u00A0账号：${slotProps.row.userName}`,
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑账户',
  '编辑账户',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    nickName: [{ required: true, message: '账户昵称不能为空', trigger: 'blur' }],
  },
  '50%',
  'inline',
);

// 资金对话框
const unCapital = async (slotProps: any) => {
  try {
    formObj.show(
      '账户资金',
      {
        id: slotProps.row.id,
        username: slotProps.row.userName,
        balance: slotProps.row.balance,
      },
      '账户资金',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};
formObj.add<any>(
  '账户资金',
  '账户资金',
  {},
  async (body) => {
    await fund(body.data);
    unGetList();
  },
  {},
);

// IP检测
const unIpCheck = async (slotProps: any) => {
  try {
    let res = await getIP(slotProps.row.id);
    formObj.show(
      'IP检测',
      {
        ...res.data,
      },
      'IP检测',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>('IP检测', 'IP检测', {}, undefined, {});

// 团队任务
const unTeamTask = async (slotProps: any) => {
  try {
    formObj.show(
      '团队任务',
      {
        userName: slotProps.row.userName,
      },
      '团队任务',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};
formObj.add<any>('团队任务', '团队任务', {}, async (body) => {}, {});
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加账户对话框 -->
        <template v-if="item == '添加账户'">
          <t-form-item label="账户类型" name="userType">
            <t-select v-model="formData.userType" placeholder="请选择账户类型">
              <t-option key="Agency" label="代理" value="Agency" />
              <t-option key="Member" label="会员" value="Member" />
              <t-option key="Test" label="测试" value="Test" />
            </t-select>
          </t-form-item>
          <t-form-item label="账户账号" name="userName">
            <t-input v-model="formData.userName" placeholder="请输入账户账号" />
          </t-form-item>
          <t-form-item label="登录密码" name="password">
            <t-input type="password" v-model="formData.password" placeholder="请输入密码" />
          </t-form-item>
          <!-- <t-form-item label="确认密码" name="confirmPassword">
            <t-input
              type="password"
              v-model="formData.confirmPassword"
              placeholder="请再次输入密码"
            />
          </t-form-item> -->
        </template>
        <!-- 编辑账户对话框 -->
        <template v-if="item == '编辑账户'">
          <t-form-item label="上级">
            <t-input v-model="formData.superiorName" :style="{ width: '440px' }" readonly placeholder="不可修改" />
          </t-form-item>
          <t-form-item label="邀请码" name="uid">
            <t-input v-model="formData.uid" :style="{ width: '440px' }" placeholder="请输入邀请码" />
          </t-form-item>
          <t-form-item label="上级ID" name="pid" help="该ID为上级ID">
            <t-input v-model="formData.pid" :style="{ width: '440px' }" readonly placeholder="不可修改" />
          </t-form-item>
          <t-form-item label="当前状态" name="state">
            <t-select v-model="formData.state" :style="{ width: '440px' }" placeholder="请选择账户状态">
              <t-option key="Normal" label="正常" value="Normal" />
              <t-option key="Locked" label="锁定" value="Locked" />
              <t-option key="Frozen" label="冻结" value="Frozen" />
              <t-option key="Kicked" label="踢下线" value="Kicked" />
            </t-select>
          </t-form-item>
          <t-form-item label="登录密码" name="password" help="登录操作时验证的密码，不修改留空">
            <t-input v-model="formData.password" type="password" :style="{ width: '440px' }" placeholder=" " />
          </t-form-item>
          <t-form-item label="取款密码" name="fundPassword" help="取款等操作时验证的密码，不修改留空">
            <t-input v-model="formData.fundPassword" type="password" :style="{ width: '440px' }" placeholder=" " />
          </t-form-item>
          <t-form-item label="任务数量" name="taskCount">
            <div class="penetrate">
              <t-input-number v-model="formData.taskCount" placeholder=" " />
            </div>
          </t-form-item>
          <t-form-item label="三级人数" name="taskCount">
            <div class="penetrate">
              <t-input v-model="formData.taskCount" :style="{ width: '440px' }" readonly placeholder=" " />
            </div>
          </t-form-item>
          <t-form-item label="充值总额" name="totalRecharge" help="只供查看，不能修改">
            <t-input v-model="formData.totalRecharge" :style="{ width: '440px' }" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="最后充值" name="lastRecharge" help="只供查看，不能修改">
            <t-input v-model="formData.lastRecharge" :style="{ width: '440px' }" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="提现总额" name="totalWithdrawals" help="只供查看，不能修改">
            <t-input v-model="formData.totalWithdrawals" :style="{ width: '440px' }" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="提现状态" name="withdrawalsState" help="当前状态">
            <t-select v-model="formData.withdrawalsState" :style="{ width: '440px' }" placeholder="请选择提现状态">
              <t-option :key="1" label="开启" :value="1" />
              <t-option :key="0" label="关闭" :value="0" />
            </t-select>
          </t-form-item>
          <t-form-item
            label="会员等级"
            name="vipLevel"
            placeholder=" "
            help="当前状态(不能修改，跟vip会员有关联,需要改名会员)"
          >
            <t-select v-model="formData.vipLevel" :style="{ width: '440px' }" placeholder="请选择会员等级" readonly>
              <t-option
                v-for="item in gradeList"
                :key="item.grade.toString()"
                :label="item.name"
                :value="item.grade.toString()"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="联系电话" name="phone">
            <t-input v-model="formData.phone" :style="{ width: '440px' }" placeholder="联系电话" />
          </t-form-item>
          <t-form-item label="信用分" name="credit">
            <div class="penetrate">
              <t-input-number v-model="formData.credit" placeholder="请输入信用分" />
            </div>
          </t-form-item>
          <t-form-item label="真实姓名" name="realName">
            <t-input v-model="formData.realName" :style="{ width: '440px' }" placeholder="请输入真实姓名" />
          </t-form-item>
          <t-form-item label="职位" name="position">
            <t-select v-model="formData.position" :style="{ width: '440px' }" placeholder="请选择职位">
              <t-option v-for="item in destList" :key="item.pid" :label="item.positionName" :value="item.pid" />
            </t-select>
          </t-form-item>
          <t-form-item label="登录次数" name="loginCount">
            <div class="penetrate">
              <t-input v-model="formData.loginCount" :style="{ width: '440px' }" readonly placeholder=" " />
            </div>
          </t-form-item>
          <t-form-item label="备注说明" name="remark">
            <t-textarea v-model="formData.remark" placeholder="操作说明" />
          </t-form-item>
        </template>
        <!-- 账户资金对话框 -->
        <template v-if="item == '账户资金'">
          <t-form-item label="账户ID" name="id">
            <div>{{ formData.id }}</div>
          </t-form-item>
          <t-form-item label="账户名称" name="username">
            <div>{{ formData.username }}</div>
          </t-form-item>
          <t-form-item label="资金操作" name="price" :help="`资金操作：正数增加，负数减少，当前:${formData.balance}`">
            <div class="capital">
              <t-input-number v-model="formData.price" placeholder="金额" />
            </div>
          </t-form-item>
          <t-form-item label="交易类型" name="type">
            <t-select v-model="formData.type">
              <t-option
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="操作说明" name="remarks">
            <t-textarea v-model="formData.remarks" placeholder="操作说明" />
          </t-form-item>
        </template>
        <!-- IP检测对话框 -->
        <template v-if="item == 'IP检测'">
          <t-form-item label="账户" name="username">
            <t-input v-model="formData.username" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="登录IP" name="lastIp">
            <t-input v-model="formData.lastIp" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="同IP账户数" name="sameIpUserCount" help="包括自己">
            <t-input v-model="formData.sameIpUserCount" readonly placeholder=" " />
          </t-form-item>
        </template>
        <!-- 团队任务对话框 -->
        <template v-if="item == '团队任务'">
          <t-form-item label="团队" name="userName">
            <div>{{ formData.userName }}</div>
          </t-form-item>
          <t-form-item label="会员等级" name="vipLevel">
            <t-select v-model="formData.vipLevel" placeholder="请选择会员等级">
              <t-option
                v-for="item in gradeList"
                :key="item.grade.toString()"
                :label="item.name"
                :value="item.grade.toString()"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="任务数量" name="taskCount">
            <div class="capital">
              <t-input-number v-model="formData.taskCount" placeholder="任务数量" />
            </div>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
  </div>
</template>

<style lang="less" scoped>
.t-textarea {
  width: 1025px;
}

.penetrate .t-input-number.t-input-number--row {
  width: 440px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}

.capital .t-input-number.t-input-number--row {
  width: 314px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}
</style>
<style>
.penetrate .t-input-number .t-input.t-align-center {
  width: 356px !important;
}

.capital .t-input-number .t-input.t-align-center {
  width: 230px !important;
}
</style>
